<!-- 图片预览页面 -->
<script setup>
  import {
    ref
  } from 'vue';
  import {
    onLoad,onShareAppMessage,onShareTimeline
  } from '@dcloudio/uni-app'
  import {
    getTitleBarHeight
  } from '@/utils/system.js'
  import {
    apiSetupScore,
    apiWriteDownLoad,
    apiDetailWall
  } from '@/api/apis.js'


  const ismask = ref(false)
  const infoPopup = ref(null)
  const scorePopup = ref(null)
  const userSorre = ref(0) //用户评分
  const classList = ref([])
  const current = ref(null) //当前的Id
  const currentIndex = ref() //当前页面的index 索引
  const readimgs = ref([]) //看过的图片存到这里
  const currentInfo = ref(null) //当前的页面的信息
  const isScore = ref(false)
  //读取本地缓存
  const Sync = uni.getStorageSync('StorgClassList') || []
  classList.value = Sync.map(item => {
    return {
      ...item,
      picurl: item.smallPicurl.replace('_small.webp', '.jpg')
    }
  })

  onLoad(async(e) => {
    current.value = e.id
    if(e.type == 'share'){
      let res = await apiDetailWall({id:current.value})
      console.log(res);
      classList.value=res.data.map((item)=>{
        return {
          ...item,
          picurl: item.smallPicurl.replace('_small.webp', '.jpg')
        }
      })
    }
    currentIndex.value = classList.value.findIndex(item => item._id == current.value)
    readimgsNewSet()
    currentInfo.value = classList.value[currentIndex.value]
  })

  function readimgsNewSet() {
    readimgs.value.push(
      currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1, //如果左边是-1的话 就把索引换到最后一张图
      currentIndex.value,
      currentIndex.value == classList.value.length - 1 ? 0 : currentIndex.value + 1 //如果已经滑到数组的最后一张就 直接变为第一张 
    ) //将每一个给存进去
    readimgs.value = [...new Set(readimgs.value)]
  }

  // 点击屏幕隐藏
  const maskChange = () => {
    ismask.value = !ismask.value
  }
  // 点击打开info弹窗
  const clickInfo = () => {
    infoPopup.value.open() //打开弹出层
  }
  // 点击关闭info弹窗
  const clickInfoClose = () => {
    infoPopup.value.close() //关闭弹出层
  }
  // 评分弹窗
  const clickScore = () => {
    // 看看有没有用户评分过 
    if (currentInfo.value.userScore) {
      isScore.value = true
      userSorre.value = currentInfo.value.userScore
    }
    scorePopup.value.open()
  }
  // 关闭评分
  const clickScoreClose = () => {
    scorePopup.value.close()
    userSorre.value = 0
    isScore.value = false
  }
  // 提交评分
  const submitScore = async () => {
    // uni.showLoading({
    //   title:'加载中...123'
    // });//提交完毕显示加载框
    let res = await apiSetupScore({
      classid: currentInfo.value.classid,
      wallId: currentInfo.value._id,
      userScore: userSorre.value
    })
    // uni.hideLoading(); //关闭评分
    if (res.errCode === 0) {
      uni.showToast({
        title: '评分成功',
        icon: 'none'
      })
      classList.value[currentIndex.value].userScore = userSorre.value
      uni.setStorageSync('StorgClassList', classList.value)
      clickScoreClose()
    }
  }
  // 点击返回上一页
  const goBack = () => {
    uni.navigateBack({
      success:()=>{
        
      },
      fail:(err)=>{
        uni.reLaunch({
          url:'/pages/index/index'
        })
      }
    })
  }

  //在swiper滑动的时候触发
  const swiperChange = (current) => {
    currentIndex.value = current.detail.current
    readimgsNewSet()
    currentInfo.value = classList.value[currentIndex.value]
  }

  const clickDownLoad = async () => {
    console.log('点击下载');
    // h5执行的
    // #ifdef H5
    uni.showModal({
      content: '请长按保存图片！',
      showCancel: false
    })
    // #endif
    // 除了h5都执行的
    // #ifndef H5
    try {
      uni.showLoading({
        title: '下载中...',
        mask: true //出现的时候不让操作任何东西
      })
      let {
        classid,
        id: wallId
      } = currentIndex.value;

      let res = await apiWriteDownLoad({
        classid,
        wallId
      })
      if (res.errCode != 0) throw res; //返回错误 走上边的try catch循环    
      uni.getImageInfo({
        src: currentInfo.value.picurl,
        success: (res) => {
          uni.saveImageToPhotosAlbum({
            filePath: res.path,
            success: (res) => {
              console.log(res);
            },
            fail: (er) => { //调用失败的接口
              if (er.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
                uni.showToast({
                  title: '保存失败，请重新下载',
                  icon: 'none'
                })
                return
              }
              uni.showModal({
                title: '授权提示',
                content: '需要授权保存相册',
                success: res => {
                  // 如果点的是confirm 就是确认按钮
                  if (res.confirm) {
                    console.log('确认了授权');
                    // 进入授权
                    uni.openSetting({
                      success(setting) {
                        console.log(res);
                        if (setting.authSetting['scope.writePhotosAlbum']) {
                          uni.showToast({
                            title: '获取授权成功',
                            icon: 'none'
                          })
                        } else {
                          uni.showToast({
                            title: '获取授权失败',
                            icon: 'none'
                          })
                        }
                      }
                    })
                  }
                }
              })
            },
            // 无论成功或者失败
            complete: () => {
              uni.hideLoading()
            }
          })
        }
      })
    } catch (err) {
      console.log(err);
      uni.hideLoading()
    }
    // #endif
  }
  
  // 分享给好友
    onShareAppMessage((e)=>{
      console.log(e);
      return {
        title:"咸虾米精选分类",
        path:'/pages/preview/preview?id='+current.value+'&type=share'
      }
    })
    
    // 分享到朋友圈
    onShareTimeline((e)=>{
      console.log(e);
      return {
        title:"咸虾米壁纸",
        query:"id"+current.value
      }
    })
</script>


<template>
  <!-- 预览页面 -->
  <view class="preview" v-if="currentInfo">

    <swiper circular :current="currentIndex" @change="swiperChange">
      <swiper-item @click="maskChange" v-for="(item,index) in classList" :key="item._id">
        <image v-if="readimgs.includes(index)" :src="item.picurl" mode="aspectFill"></image>
      </swiper-item>
    </swiper>
    {{readimgs}}
    <view class="mask" v-if="!ismask">
      <!-- 左上角返回按钮 点击 -->
      <view class="goBack" :style="{top:getTitleBarHeight() + 'px'}" @click="goBack">
        <uni-icons type="back" size="20" color="#fff"></uni-icons>
      </view>
      <view class="count">{{currentIndex+1}} /{{classList.length}}</view>
      <view class="time">
        <uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
      </view>
      <view class="date"><uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat></view>
      <view class="fotter">

        <view class="box" @click="clickInfo">
          <uni-icons type="info" size="28"></uni-icons>
          <view class="text">信息</view>
        </view>

        <view class="box" @click="clickScore">
          <uni-icons type="star" size="28"></uni-icons>
          <view class="text">{{currentInfo?.score}}分</view>
        </view>

        <view class="box" @click="clickDownLoad">
          <uni-icons type="download" size="23"></uni-icons>
          <view class="text">下载</view>
        </view>

      </view>
    </view>
    <!-- ----------------------------------------------------- -->
    <uni-popup ref="infoPopup" type="bottom" :safe-area="false">
      <view class="infoPopup">
        <view class="popHeader">
          <view></view>
          <view class="title">壁纸信息</view>
          <view class="close" @click="clickInfoClose">
            <uni-icons type="closeempty" size="18" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view scroll-y>
          <view class="content">

            <view class="row">
              <view class="label">壁纸ID:</view>
              <!-- selectable属性可以被选中 -->
              <text selectable class="value">{{currentInfo?._id}}</text>
            </view>

            <view class="row">
              <view class="label">分类:</view>
              <!-- selectable属性可以被选中 -->
              <text selectable class="value class">{{currentInfo?.tabs[0]}}</text>
            </view>

            <view class="row">
              <view class="label">发布者:</view>
              <!-- selectable属性可以被选中 -->
              <text selectable class="value">{{currentInfo?.nickname}}</text>
            </view>

            <view class="row">
              <view class="label">评分:</view>
              <view class="value roteBox">
                <uni-rate readonly touchcancel :max="5" :value="5" />
                <text class="score">{{currentInfo?.score}}分</text>
              </view>
            </view>

            <view class="row">
              <view class="label">摘要:</view>
              <!-- selectable属性可以被选中 -->
              <view class="value">{{currentInfo?.description}}</view>
            </view>

            <view class="row">
              <view class="label">标签:</view>
              <!-- selectable属性可以被选中 -->
              <view class="value tabs">
                <view class="tab" v-for="item in currentInfo?.tabs" :key="item">
                  {{item}}
                </view>
              </view>
            </view>

            <view class="copyright">声明：本图片来自用户投稿：非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID到平台，邮箱513894357@qq.com，管理将删除壁纸，维护您的权益
            </view>

          </view>
        </scroll-view>
      </view>
    </uni-popup>
    <!-- 评分弹窗 -->
    <uni-popup ref="scorePopup" :is-mask-click="false">
      <view class="scorePupup">

        <view class="popHeader">C
          <view></view>
          <view class="title">{{isScore ? '评分过了':'壁纸评分'}}</view>
          <view class="close" @click="clickScoreClose">
            <uni-icons type="closeempty" size="18" color="#999"></uni-icons>
          </view>
        </view>

        <view class="content">
          <uni-rate v-model="userSorre" allowHalf :disabled="isScore" disabled-color="#FFCA3E" />
          <text class="text">{{userSorre}}分</text>
        </view>

        <view class="footer">
          <button @click="submitScore" :disabled="!userSorre || isScore" class="default" size="mini" plain>确认评分</button>
        </view>

      </view>
    </uni-popup>
  </view>
</template>


<style lang="scss" scoped>
  .preview {
    position: relative;
    width: 100%;
    height: 100vh;

    .popHeader {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        color: $text-font-color-2;
        font-size: 26rpx;
      }

      .close {
        padding: 6rpx;
      }
    }

    .scorePupup {
      background-color: #fff;
      padding: 30rpx;
      width: 70vw;
      border-radius: 30rpx;

      .content {
        padding: 30rpx 0;
        display: flex;
        justify-content: center;
        align-items: center;

        .text {
          color: #ffca3e;
          padding-left: 10rpx;
          width: 80rpx;
          line-height: 1em;
          text-align: right;
        }
      }

      .footer {
        display: flex;
        padding: 10rpx 0;
        align-items: center;
        justify-content: center;
      }
    }

    .infoPopup {
      background-color: #fff;
      padding: 30rpx;
      border-radius: 30rpx 30rpx 0 0;
      overflow: hidden;

      scroll-view {
        max-height: 60vh;

        .row {
          display: flex;
          padding: 16rpx 0;
          font-size: 32rpx;
          line-height: 1.7em;

          .label {
            color: $text-font-color-3;
            width: 140rpx;
            text-align: right;
            font-size: 30rpx;
          }

          .value {
            flex: 1;
            width: 0;
          }

          .roteBox {
            display: flex;
            align-items: center;

            .score {
              font-size: 26rpx;
              color: $text-font-color-2;
              padding-left: 10rpx;
            }
          }

          .tabs {
            display: flex;
            flex-wrap: wrap;

            .tab {
              border: 1px solid $brand-theme-color;
              color: $brand-theme-color;
              font-size: 22rpx;
              padding: 15rpx 30rpx;
              border-radius: 40rpx;
              line-height: 1em;
              margin: 0 10rpx 10rpx 15rpx;
            }
          }

          .class {
            color: $brand-theme-color ;
          }
        }

        .copyright {
          color: #666;
          font-size: 28rpx;
          padding: 20rpx;
          border-radius: 10rpx;
          background-color: #F6F6F6;
          margin: 20rpx 0;
          line-height: 1.6rem;
        }
      }
    }

    .mask {
      &>view {
        position: absolute;
        left: 0;
        right: 0;
        margin: auto;
        color: #fff;
        width: fit-content;
      }

      .goBack {
        width: 38px;
        height: 38px;
        background-color: rgba(0, 0, 0, 0.5);
        left: 30rpx;
        margin-left: 0%;
        border-radius: 100px;
        top: 0;
        backdrop-filter: blur(10rpx);
        border: 1rpx solid rgba(255, 255, 255, 0.3);
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .count {
        top: 10vh;
        width: fit-content;
        background-color: rgba(0, 0, 0, 0.3);
        font-size: 28rpx;
        border-radius: 40rpx;
        padding: 8rpx 28rpx;
      }

      .time {
        top: calc(10vh + 80rpx);
        font-size: 140rpx;
        font-weight: 100;
        line-height: 1em;
        text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
      }

      .date {
        font-size: 34rpx;
        top: calc(10vh + 230rpx);
        text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
      }

      .fotter {
        background: rgba(255, 255, 255, 0.8);
        bottom: 10vh;
        width: 65vw;
        height: 120rpx;
        border-radius: 120rpx;
        color: #000;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
        backdrop-filter: blur(20rpx);
        padding: 2rpx 15rpx;

        .box {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 2rpx 12rpx;

          .text {
            font-size: 26rpx;
            color: $text-font-color-2 ;
          }
        }
      }
    }

    swiper {
      width: 100%;
      height: 100%;

      image {
        width: 100%;
        height: 100vh;
      }
    }
  }
</style>